<template>
  <div class="contact">
    <div class="contact-list">
      <div
        class="contact-item"
        v-for="item in contactList"
        :key="item.key"
        :class="{'is_current': currentKey === item.key}"
        @click="currentKey = item.key"
      >{{item.label}}</div>
    </div>
    <div class="contact-content">
      <div class="paper-info" v-if="showPaperInfo()">
        <div class="paper-score">
          <span>试题数量:</span>
          <span class="paper-num">{{questionCount}}</span>
          <span>试题总分:</span>
          <span class="paper-num">{{totalScore}}</span>
        </div>
        <div class="answer-container">
          <div class="answer-title">答题卡</div>
          <div class="answer-list">
            <div class="answer-item">
              <div class="question-num">题号</div>
              <div class="question-num">
                <span>得分</span>
                <el-input
                  size="small"
                  class="cus-input"
                  @change="setTempScore"
                  v-model.number="rightScore"
                >
                  <template #append>分</template>
                </el-input>
              </div>
            </div>
            <div
              class="answer-item"
              v-for="item in currentKey === 'handout' ? handoutCharpts : paperCharpts"
              :key="item.id"
            >
              <div class="item-container">
                <span v-html="currentKey === 'handout' ? item.content :item.title"></span>
              </div>
              <div class="item-container">
                <el-radio-group
                  v-model="item.correct"
                  :disabled="item.isDisabled"
                  @change="charptsChanged($event, item)"
                >
                  <el-radio :label="1">全对</el-radio>
                  <el-radio :label="0">全错</el-radio>
                </el-radio-group>
              </div>
              <div class="answer-child" v-for="(child, index) in item.questions" :key="child.id">
                <div>{{index+1}}</div>
                <div>
                  <el-radio-group
                    @change="childChanged($event, item, child)"
                    v-model="child.correct"
                    :disabled="child.isDisabled"
                  >
                    <el-radio :label="1">对</el-radio>
                    <el-radio :label="0">错</el-radio>
                  </el-radio-group>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="paper-container">
        <template
          v-if="((classData && classData.child && classData.child.type === 1) || directType === 1) && currentKey === 'handout'"
        >
          <iframe
            :src="`${basePath}${classData.child.path}`"
            frameborder="0"
            width="100%"
            height="100%"
            style="min-height:550px"
            v-if="classData && classData.child"
          ></iframe>
          <iframe
            :src="`${basePath}${previewPath}`"
            frameborder="0"
            width="100%"
            height="100%"
            style="min-height:550px"
            v-else
          ></iframe>
        </template>
        <HandoutPreviewComponent
          v-else-if="currentKey === 'handout' && handoutId"
          :answerShow='true'
          class-preview
          :handout="handoutId"
        />
        <TestPaperPreview
          v-else-if="currentKey !== 'handout' && testPaperId"
          :previewNoRoute="true"
          :idNoRoute="testPaperId"
          :answerShow='true'
        />
        <cus-empty v-else></cus-empty>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { ref, computed, nextTick, watch } from 'vue'
import axios from 'axios'
import TestPaperPreview from '@/views/test-paper/update/index.vue'
import HandoutPreviewComponent from '@/views/handout/index.vue'
import paperStore from '@/views/test-paper/update/store/index'
import hanoutStore from '@/views/handout/store/index'
import store from './../../../store'
import $ from '$'
import { ElMessage } from 'element-plus'
export default {
  components: { TestPaperPreview, HandoutPreviewComponent },
  props: {
    studentId: {
      type: String,
      default: '',
    },
    data: {
      type: Object,
      default: {},
    },
    commentDetail: {
      type: Object,
      default: {},
    },
  },
  setup(props) {
    let contactList = [
      { label: '进门考', key: 'test' },
      { label: '讲义练习题', key: 'handout' },
      { label: '上节课作业', key: 'homework' },
    ]
    let currentKey = ref('handout')
    watch(currentKey, () => {
      questionCount.value = 0
      totalScore.value = 0
      paperCharpts.value = []
      getScoreDetail()
      if (currentKey.value === 'test') {
        getPaper()
      } else if (currentKey.value === 'homework') {
        getHomeWork()
      }
    })
    let paperCharpts = ref()
    let handoutCharpts: any = ref()
    let totalScore = ref(0)
    let paperInfo: any = computed(() => paperStore.state.paperInfo)
    let handoutInfo: any = computed(() => hanoutStore.state.paperInfo)
    let classData: any = computed(() => store.state.classData)
    let directType: any = computed(() => store.state.directType)
    let previewPath: any = computed(() => store.state.filePath)
    let handoutId = computed(
      () => store.state.handoutId || (classData.value!= null ? classData.value.child.handoutId : "")
    )
    let testPaperId = ref()
    let questionCount = ref(0)
    let rightScore = ref(0)
    let countScoreList = ref([])
    let detailScoreList: any = ref([])
    let ScoreData = ref({
      test: props.commentDetail.entranceScore || 0,
      handout: props.commentDetail.practiceScore || 0,
      homework: props.commentDetail.lastHomeworkScore || 0,
    })
    let basePath = $.utils.generatBasePath() + `furl=${import.meta.env.VITE_APP_BASE_URL}`;
    let lessonTimeId: any = ref('')
    watch(paperInfo, () => {
      getPaperQuestions()
    })
    const getRightScore = () => {
      return (
        eval(
          countScoreList.value
            .filter((e: any) => e.correct === 1 && e.pid)
            .map((e: any) => e.score)
            .join('+')
        ) || 0
      )
    }
    const getPaperTotalScore = () => {
      return paperCharpts.value.reduce((sum, item) => {
        return (sum += item.questions.reduce((score, child) => {
          return (score += child.correct === 1 ? child.score : 0)
        }, 0))
      }, 0)
    }
    const getPaper = () => {
      testPaperId.value = ''
      axios
        .post('/admin/lessonEntranceExam/query', {
          lessonTimeId: classData.value ? classData.value.id : props.data.id,
        })
        .then((res: any) => {
          if (res.json && res.json.length > 0) {
            testPaperId.value = res.json[0].paperId
            getPaperQuestions()
          }
        })
    }
    const getHomeWork = () => {
      testPaperId.value = ''
      axios
        .post('/admin/lessonHomework/queryLastByLessonId', {
          lessonId:
            props.data.type === 1 ? props.data.contractId : props.data.lessonId,
          lessonThirdId: props.data.thirdId,
          type: props.data.type,
        })
        .then((res: any) => {
          if (res.json) {
            testPaperId.value = res.json.paperId
            lessonTimeId.value = res.json.lessonTimeId
            getPaperQuestions()
          }
        })
    }
    const getScoreDetail = () => {
      axios
        .post('/admin/lessonSummaryDetails/query', {
          studentId: props.studentId,
          lessonId:
            props.data.type === 1 ? props.data.contractId : props.data.lessonId,
          lessonThirdId: props.data.thirdId,
          type: { test: 1, handout: 2, homework: 3 }[currentKey.value],
        })
        .then((res: any) => {
          res.result && (detailScoreList.value = res.json)
          currentKey.value === 'handout' && getHandoutQuestions()
          currentKey.value !== 'handout' && getPaperQuestions()
        })
    }
    getScoreDetail()
    /** 获取讲义中的练习题 */
    const getHandoutQuestions = () => {
      let scoreList = $.clone(handoutInfo.value.content)
      // 1、铺平知识元
      scoreList.forEach((item, index) => {
        if (item.type === 3 && item.child) {
          scoreList.splice(index, 1, ...item.child)
        }
      })
      //  插一步-----计算总分以及题目数量
      countScoreList.value = scoreList
      totalScore.value = scoreList.reduce((sum, item) => {
        return (sum += item.pid && item.type === 4 ? item.score : 0)
      }, 0)
      // 2、取出标题
      const titleList = scoreList.filter((e) => !e.pid)
      // 3、将标题包含的子集放入child
      titleList.forEach((f) => {
        f.questions = []
        scoreList.forEach((child) => {
          // 回显评分详情
          let scoreItemIndex
          child.question &&
            (scoreItemIndex = detailScoreList.value.findIndex(
              (e: any) => e.questionId === child.question.id
            ))
          // scoreItemIndex > -1 &&
          //   (child.correct = detailScoreList.value[scoreItemIndex].correct);
          if (scoreItemIndex > -1) {
            child.correct = detailScoreList.value[scoreItemIndex].correct
            // child.isDisabled = true;
            // f.id === child.pid && (f.isDisabled = true);
          }
          if (f.id === child.pid && (child.type === 4 || child.type === 8)) {
            f.questions.push(child)
            child.correct === 1
              ? (f.correct = f.questions.every((e) => e.correct === 1) ? 1 : 2)
              : (f.correct = f.questions.every((e) => e.correct === 0) ? 0 : 2)
          }
        })
      })
      rightScore.value = ScoreData.value[currentKey.value]
      // 4、将剩余题目放入其他中
      let otherQ = scoreList.filter((e) => {
        return (
          titleList.findIndex((t) => t.id === e.pid) < 0 &&
          e.pid &&
          (e.type === 4 || e.type === 8)
        )
      })
      questionCount.value =
        scoreList.filter(
          (e) => titleList.findIndex((t) => e.pid === t.id) > -1 && e.type === 4
        ).length + otherQ.length
      handoutCharpts.value = [
        ...titleList,
        {
          content: '其他',
          questions: otherQ,
          id: 'qt',
        },
      ].filter((e) => e.questions.length > 0)
    }
    /** 获取试卷中的练习题 */
    const getPaperQuestions = () => {
      if (!testPaperId.value) {
        return []
      }
      totalScore.value = paperInfo.value.paperCharpts.reduce((sum, item) => {
        return (sum += item.totalScore)
      }, 0)
      questionCount.value = paperInfo.value.paperCharpts.reduce((sum, item) => {
        return (sum += item.questions.length)
      }, 0)
      let detailPaperScore = $.clone(paperInfo.value.paperCharpts)
      rightScore.value = ScoreData.value[currentKey.value]
      detailPaperScore.forEach((ele) => {
        if (ele.questions && ele.questions.length > 0) {
          ele.questions.forEach((child) => {
            let scoreItemIndex
            child.question &&
              (scoreItemIndex = detailScoreList.value.findIndex(
                (e: any) => e.questionId === child.question.id
              ))
            // scoreItemIndex > -1 &&
            //   (child.correct = detailScoreList.value[scoreItemIndex].correct);
            if (scoreItemIndex > -1) {
              child.correct = detailScoreList.value[scoreItemIndex].correct
              // child.isDisabled = true;
              // ele.isDisabled = true;
            }
            child.correct === 1
              ? (ele.correct = ele.questions.every((e) => e.correct === 1)
                  ? 1
                  : 2)
              : (ele.correct = ele.questions.every((e) => e.correct === 0)
                  ? 0
                  : 2)
          })
        }
      })
      paperCharpts.value = detailPaperScore
    }
    getHandoutQuestions()
    /** 全对、全错 */
    const charptsChanged = (val, data) => {
      const params = data.questions.map((ele) => {
        ele.correct = val
        return {
          lessonId: props.data.type === 1 ? props.data.contractId : props.data.lessonId,
          lessonThirdId: props.data.thirdId,
          indexId: classData.value ? classData.value.id : '',
          studentId: props.studentId,
          studentName: props.commentDetail.studentName,
          type: { test: 1, handout: 2, homework: 3 }[currentKey.value],
          questionId: ele.questionId || ele.question.id,
          correct: ele.correct,
          lessonType: props.data.type,
          socre: ele.score,
          lessonTimeId:
            currentKey.value === 'homework' ? lessonTimeId.value : '',
        }
      })
      rightScore.value =
        currentKey.value === 'handout' ? getRightScore() : getPaperTotalScore()
      setTempScore(
        currentKey.value === 'handout' ? getRightScore() : getPaperTotalScore()
      )
      saveScoring(params)
    }
    /** 单个题目打分 */
    const childChanged = (val, data, qus) => {
      val === 1
        ? (data.correct = data.questions.every((e) => e.correct === 1) ? 1 : 2)
        : (data.correct = data.questions.every((e) => e.correct === 0) ? 0 : 2)
      rightScore.value =
        currentKey.value === 'handout' ? getRightScore() : getPaperTotalScore()
      setTempScore(
        currentKey.value === 'handout' ? getRightScore() : getPaperTotalScore()
      )
      const params = [
        {
          lessonId: props.data.type === 1 ? props.data.contractId : props.data.lessonId,
          lessonThirdId: props.data.thirdId,
          indexId: classData.value ? classData.value.id : '',
          studentId: props.studentId,
          studentName: props.commentDetail.studentName,
          type: { test: 1, handout: 2, homework: 3 }[currentKey.value],
          questionId: qus.questionId || qus.question.id,
          correct: qus.correct,
          lessonType: props.data.type,
          socre: qus.score,
          lessonTimeId:
            currentKey.value === 'homework' ? lessonTimeId.value : '',
        },
      ]
      saveScoring(params)
    }
    /** 保存打分结果 */
    const saveScoring = (params) => {
      axios
        .post('/admin/lessonSummaryDetails/batchSave', params, {
          headers: { 'Content-Type': 'application/json' },
        })
        .then((res: any) => {
          !res.result && ElMessage.error(res.msg)
        })
      saveOnlyScore()
    }
    /** 仅保存打分分数 */
    const saveOnlyScore = () => {
      let scoreParams = {
        id: props.commentDetail.id,
        entranceScore: ScoreData.value['test'],
        practiceScore: ScoreData.value['handout'],
        lastHomeworkScore: ScoreData.value['homework'],
        lessonThirdId: props.data.thirdId,
        contractId: props.data.contractId,
      }
      axios
        .post('/admin/lessonSummary/saveOrUpdate', scoreParams)
        .then((res: any) => {
          !res.result && ElMessage.error(res.msg)
        })
    }
    /** 是否展示左侧题目 */
    const showPaperInfo = () => {
      if (currentKey.value === 'handout') {
        return handoutCharpts.value && handoutCharpts.value.length > 0
      } else {
        return paperCharpts.value && paperCharpts.value.length > 0
      }
    }
    /** 手动输入分数暂存 */
    const setTempScore = (val) => {
      ScoreData.value[currentKey.value] = val
    }
    return {
      contactList,
      currentKey,
      paperCharpts,
      charptsChanged,
      totalScore,
      paperInfo,
      handoutId,
      classData,
      childChanged,
      handoutInfo,
      getHandoutQuestions,
      handoutCharpts,
      questionCount,
      rightScore,
      saveScoring,
      countScoreList,
      getRightScore,
      testPaperId,
      getPaperQuestions,
      getScoreDetail,
      detailScoreList,
      getHomeWork,
      getPaperTotalScore,
      showPaperInfo,
      ScoreData,
      setTempScore,
      saveOnlyScore,
      lessonTimeId,
      previewPath,
      basePath,
      directType,
    }
  },
}
</script>

<style scoped lang="scss">
.contact {
  .contact-list {
    display: flex;
    border-bottom: 1px solid #ebf0fc;
    .contact-item {
      padding: 12px 20px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #77808d;
      cursor: pointer;
    }
    .is_current {
      color: #72b22a;
      position: relative;
      &::after {
        content: '';
        position: absolute;
        left: 9px;
        right: 9px;
        bottom: 0;
        height: 4px;
        background: #72b22a;
        border-radius: 2px;
      }
    }
  }
  .contact-content {
    max-height: 70vh;
    min-width: 740px;
    overflow: auto;
    display: flex;
    .paper-info {
      width: 30%;
      min-width: 330px;
      .paper-score {
        padding: 10px;
        :nth-child(3) {
          margin-left: 40px;
        }
        > span {
          font-size: 14px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #77808d;
        }
        .paper-num {
          font-size: 14px;
          font-family: PingFangSC-Medium, PingFang SC;
          font-weight: 500;
          color: #333333;
          margin-left: 10px;
        }
      }
      .answer-container {
        .answer-title {
          border-radius: 4px 4px 0px 0px;
          padding: 7px 0 19px 0;
          text-align: center;
          background: #72b22a;
          font-size: 14px;
          font-family: PingFangSC-Medium, PingFang SC;
          font-weight: 500;
          color: #ffffff;
        }
        .answer-list {
          margin-top: -12px;
          display: grid;
          grid-gap: 1px;
          grid-template: auto / auto;
          border-radius: 4px 4px 0px 0px;
          border: 1px solid #ebeef5;
          background: #ebeef5;
          max-height: 60vh;
          overflow: auto;
          .answer-item {
            display: grid;
            grid-gap: 1px;
            grid-template: auto / repeat(2, calc(50% - 0.5px));
            > .item-container {
              background: #f5f7fa;
              padding: 10px 10px;
              display: flex;
              justify-content: center;
              align-items: center;
            }
            .question-num {
              padding: 5px 20px;
              background: #ffffff;
              display: flex;
              justify-content: center;
              align-items: center;
              > span {
                white-space: nowrap;
                margin-right: 8px;
              }
              :deep(.el-input__inner) {
                border-right: #fff;
              }
              :deep(.el-input-group__append) {
                background-color: #fff;
                padding: 0 8px;
                position: relative;
                &::after {
                  content: '';
                  position: absolute;
                  top: 8px;
                  bottom: 8px;
                  left: 0;
                  width: 1px;
                  background-color: #dcdfe6;
                }
              }
            }
            .answer-child {
              background: #ebeef5;
              grid-column-start: 1;
              grid-column-end: 3;
              display: grid;
              grid-gap: 1px;
              grid-template: auto / repeat(2, calc(50% - 0.5px));
              > div {
                padding: 10px 0;
                display: flex;
                justify-content: center;
                align-items: center;
                background: #ffffff;
              }
            }
          }
        }
      }
    }
    .paper-container {
      flex: 1;
      overflow: hidden;
      padding-top: 30px;
    }
    :deep(.paper_container) {
      padding: 0 30px;
      height: 100%;
      overflow: auto;
    }
    :deep(.content) {
      height: 100%;
      // min-height: 50vh;
    }
  }
}
</style>
